<template>
  <div class="inventory-header">
    <el-form :inline="true" :model="formInline" @submit.native.prevent="handleSearch">
      <el-form-item label="出入库单号:">
        <el-input v-model="formInline.transactionCode" placeholder="请输入出入库单号" @input="handleSearch"></el-input>
      </el-form-item>
      <el-form-item label="类型:">
        <el-select v-model="formInline.type" placeholder="请选择类型" style="width: 100px" clearable @change="handleSearch">
          <el-option label="入库" :value="1"></el-option>
          <el-option label="出库" :value="2"></el-option>
          <el-option label="全部" :value="null"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="来源/去向:">
        <el-input v-model="formInline.source" placeholder="请输入来源/去向" @input="handleSearch"></el-input>
      </el-form-item>
      <el-form-item label="备注:">
        <el-input v-model="formInline.remark" placeholder="请输入备注" @input="handleSearch"></el-input>
      </el-form-item>
      <el-form-item label="创建时间:">
        <el-date-picker
          v-model="formInline.dateRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
    </el-form>
  </div>

  <div class="inventory-table">
    <el-table :data="inventoryData" v-loading="loading" style="width: 100%">
      <el-table-column label="出入库单号" width="180">
        <template #default="scope">
          <el-button type="text" @click="handleViewDetails(scope.row)">
            {{ scope.row.transactionCode }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="100">
        <template #default="scope">
          {{ scope.row.type === 1 ? '入库' : '出库' }}
        </template>
      </el-table-column>
      <el-table-column prop="source" label="来源/去向" width="150" />
      <el-table-column prop="total" label="件数" width="80" />
      <el-table-column prop="totalPrice" label="总吊牌价" width="120" />
      <el-table-column prop="createUserName" label="创建人" width="150" />
      <el-table-column prop="createTime" label="创建时间" width="150" />
      <el-table-column prop="remark" label="备注" width="300" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 0"
            type="text"
            @click="handleDeleteTransaction(scope.row.id)"
          >
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-drawer title="出入库单详情" v-model="drawerVisible" :direction="direction" size="70%">
    <div v-if="inventoryDetails">
      <div class="drawer-actions">
        <Tinder
          v-if="currentInventory.status === 0"
          type="danger"
          @click="handleDeleteTransaction(currentInventory.id)"
        >
          <el-button type="danger" size="small">
            删除出入库单
          </el-button>
        </Tinder>
      </div>
      <el-table :data="inventoryDetails" border style="width: 100%">
        <el-table-column
          v-for="column in tableDetailsLabel"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
        >
          <template v-if="column.prop === 'sizeType'" #default="scope">
            {{ sizeTypeMap[scope.row.sizeType] || scope.row.sizeType }}
          </template>
          <template v-else-if="column.prop === 'retailPrice'" #default="scope">
            {{ scope.row.retailPrice.toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-drawer>

  <el-pagination
    v-model:current-page="config.page"
    v-model:page-size="config.pageSize"
    :page-sizes="[10, 20, 30]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="config.total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
</template>

<script setup>
import { ElMessage, ElDrawer, ElMessageBox } from 'element-plus';
import { ref, reactive, onMounted } from 'vue';
import dayjs from 'dayjs';
import api from '@/api';

const formInline = reactive({
  transactionCode: '',
  type: null,
  source: '',
  remark: '',
  dateRange: []
});

const config = reactive({
  page: 1,
  pageSize: 10,
  transactionCode: '',
  type: null,
  source: '',
  remark: '',
  beginTime: '',
  endTime: '',
  total: 0
});

const inventoryData = ref([]);
const loading = ref(false);

const inventoryDetails = ref(null);
const currentInventory = ref(null);
const drawerVisible = ref(false);
const direction = ref('rtl');

const tableDetailsLabel = reactive([
  { prop: 'brand', label: '品牌', width: '150' },
  { prop: 'productCode', label: '商品款号', width: '150' },
  { prop: 'color', label: '颜色', width: '120' },
  { prop: 'sizeType', label: '尺码类型', width: '120' },
  { prop: 'retailPrice', label: '吊牌价', width: '120' },
  { prop: 'createTime', label: '入库时间', width: '150' }
]);

const sizeTypeMap = {
  0: 'F',
  1: 'XS',
  2: 'S',
  3: 'M',
  4: 'L',
  5: 'XL',
  6: '2XL',
  7: '3XL'
};

const handleSearch = () => {
  if (Array.isArray(formInline.dateRange) && formInline.dateRange.length === 2) {
    config.beginTime = dayjs(formInline.dateRange[0])
      .startOf('day')
      .format('YYYY-MM-DD HH:mm:ss');
    config.endTime = dayjs(formInline.dateRange[1])
      .endOf('day')
      .format('YYYY-MM-DD HH:mm:ss');
  } else {
    config.beginTime = '';
    config.endTime = '';
  }

  config.transactionCode = formInline.transactionCode.trim();
  config.type = formInline.type;
  config.source = formInline.source.trim();
  config.remark = formInline.remark.trim();
  config.page = 1;
  getInventoryData();
};

const getInventoryData = async () => {
  loading.value = true;
  try {
    const data = await api.inventoryTransaction.getInventoryTransaction({
      ...config,
      mock: false
    });
    inventoryData.value = data.data.records.map(item => ({
      ...item,
      createTime: dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss')
    }));
    config.total = data.data.total;
  } catch (error) {
    ElMessage.error(error.message || '获取出入库单数据失败');
  } finally {
    loading.value = false;
  }
};

const getInventoryDetails = async (id) => {
  try {
    const data = await api.inventoryTransaction.getInventoryTransactionDetails({
      InventoryTransactionId: id,
      mock: false
    });
    inventoryDetails.value = data.data.map(item => ({
      ...item,
      createTime: dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss')
    }));
    drawerVisible.value = true;
  } catch (error) {
    ElMessage.error(error.message || '获取出入库单详情失败');
  }
};

const handleDeleteTransaction = (id) => {
  ElMessageBox.confirm(`确定要删除该出入库单吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await api.inventoryTransaction.checkInventoryTransaction({
          InventoryTransactionId: id,
          status: 2,
          mock: false
        });
        ElMessage.success('删除成功');
        drawerVisible.value = false;
        getInventoryData();
      } catch (error) {
        ElMessage.error(error.message || '删除失败，请稍后再试');
      }
    })
    .catch(() => {});
};

const handleViewDetails = (row) => {
  currentInventory.value = row;
  getInventoryDetails(row.id);
};

const handleSizeChange = (pageSize) => {
  config.pageSize = pageSize;
  config.page = 1;
  getInventoryData();
};

const handleCurrentChange = (page) => {
  config.page = page;
  getInventoryData();
};

onMounted(() => {
  getInventoryData();
});
</script>

<style scoped>
.inventory-header {
  display: flex;
  justify-content: space-between;
}

.inventory-table {
  width: 100%;
}

.el-button {
  margin: 0;
}

.drawer-actions {
  text-align: right;
  margin-bottom: 20px;
}
</style>